package com.example.icar;

import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

//import com.example.icar.mqtt.MqttManager;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import com.example.icar.rosmaster.RosmasterClient;
import com.example.icar.rosmaster.RosmasterHttpClient;
import com.example.icar.rosmaster.RosmasterLib;
import com.example.icar.rosmaster.RosmasterWifi;

//import org.eclipse.paho.android.service.MqttAndroidClient;
//import org.eclipse.paho.client.mqttv3.IMqttActionListener;
//import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
//import org.eclipse.paho.client.mqttv3.IMqttToken;
//import org.eclipse.paho.client.mqttv3.MqttCallback;
//import org.eclipse.paho.client.mqttv3.MqttCallbackExtended;
//import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
//import org.eclipse.paho.client.mqttv3.MqttException;
//import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import android.util.Base64;
import com.example.icar.rosmaster.RosmasterCamera;
import com.example.icar.rosmaster.RosmasterClient;
import com.example.icar.rosmaster.RosmasterHttpClient;
import com.example.icar.rosmaster.RosmasterLib;
import com.example.icar.rosmaster.RosmasterWifi;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;


public class MainActivity extends AppCompatActivity implements RosmasterWifi.ServerCallback {

//    private MqttManager mqttManager;

    private static final String TAG = "MainActivity";

    // 端口常量
    private static final int CONTROL_PORT = 6000;  // TCP控制端口
    private static final int HTTP_PORT = 6500;     // HTTP服务器端口

    // 权限请求码
    private static final int PERMISSION_REQUEST_CODE = 100;

    // UI元素
    private TextView statusText;
    private TextView connectionStatus;
    private EditText ipAddressEdit;
    private EditText portEdit;
    private Button connectButton;
    private Button startServerButton;
    private ProgressBar connectionProgress;

    private ImageView logoImage;
    private String deviceSecret = "7c7884e400e4d6d8fb20b2c738ba1124";
    // 布局
    private View rootView;

    // 线程池
    private ExecutorService executorService;
    private Handler mainHandler;

    // Rosmaster库
    private RosmasterLib rosmasterLib;
    private RosmasterClient rosmasterClient;
    private RosmasterHttpClient rosmasterHttpClient;
    private RosmasterWifi rosmasterWifi;

    // 连接状态
    private boolean isConnected = false;
    private boolean isServerMode = false;
    private String currentIpAddress = "";

    // 默认速度
    private static final int DEFAULT_SPEED = 50;

    // 网络状态监听
    private BroadcastReceiver networkReceiver;


    //MQTT
    private  String deviceId = "IOT-TEST-001_IoT_TEST_001";
    private String requestId;
    private String shadowGetTopic;
    private String shadowResponseTopic;
    private String shadowDeltaTopic;
    private  String getTopicDown;
    private MqttClient mqttClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //生成唯一的requestid
        requestId = UUID.randomUUID().toString();

        // 构建主题 (匹配您的 Python 代码)
        shadowGetTopic = "$oc/devices/" + deviceId + "/sys/shadow/get/request_id=" + requestId;
        shadowResponseTopic = "$oc/devices/" + deviceId + "/sys/shadow/get/response/request_id=" + requestId;
        shadowDeltaTopic = "$oc/devices/" + deviceId + "/sys/shadow/update/delta"; // 影子变更通知主题
        getTopicDown = "$oc/devices/" + deviceId + "/sys/messages/down";
// 连接并订阅 MQTT (在后台线程中运行)
        new Thread(() -> {
            try {
                // 设置 MQTT 客户端 (替换代理 URL，例如 "tcp://your-broker:1883")
                String broker = "tcp://220e31623e.st1.iotda-device.cn-north-4.myhuaweicloud.com:1883";
                String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
//                long currentTimeInMillis = System.currentTimeMillis(); // 毫秒
//                long currentTimeInSeconds = currentTimeInMillis / 1000; // 转换为秒
//
//                // 生成客户端 ID
//                String clientId = "IOT-TEST-001_IoT_TEST_001_0_0_" + currentTimeInSeconds;
//                Log.d(TAG, "clientId: " + clientId);
                String clientId ="IOT-TEST-001_IoT_TEST_001_0_0_2025071009";
                mqttClient = new MqttClient(broker, clientId, new MemoryPersistence());

                MqttConnectOptions options = new MqttConnectOptions();
                options.setCleanSession(true);
                options.setUserName(deviceId); // 如果需要认证
                String password = "9a142df89c269eabc7c745c264c0015926c43ac1679687537714692bb9efbac8";
                options.setPassword(password.toCharArray());

                mqttClient.setCallback(new MqttCallback() {
                    @Override
                    public void connectionLost(Throwable cause) {
                        // 处接丢失
                        Log.e("MQTT", "连接丢失: " + cause.getMessage());

                        // 自动重连
                        try {
                            Log.d("MQTT", "尝试重新连接...");
                            mqttClient.connect(options);
                            mqttClient.subscribe(shadowResponseTopic, 1); // 重新订阅
                            Log.d("MQTT", "重新订阅成功");
                        } catch (MqttException e) {
                            Log.e("MQTT", "重连失败: " + e.getMessage());
                        }
                    }

                    @Override
                    public void messageArrived(String topic, MqttMessage message) throws Exception {
                        // 处理接收到的消息
                        String messagePayload = new String(message.getPayload(), StandardCharsets.UTF_8);
                        Log.d("MQTT", "消息到达 " + topic + ": " + messagePayload);

                        // 解析 JSON 数据
                        try {
                            JSONObject jsonResponse = new JSONObject(messagePayload);
                            JSONArray shadowArray = jsonResponse.getJSONArray("shadow");
                            JSONObject shadowObject = shadowArray.getJSONObject(0); // 获取第一个影子数据对象

                            String serviceId = shadowObject.getString("service_id");
                            JSONObject reportedProperties = shadowObject.getJSONObject("reported").getJSONObject("properties");
                            String eventTime = shadowObject.getJSONObject("reported").getString("event_time");

                            // 提取属性数据
                            int testData = reportedProperties.optInt("Test_data", -1);
                            int gasValue = reportedProperties.optInt("gas_value", -1);
                            String unit = reportedProperties.optString("unit", "");
                            int illumination = reportedProperties.optInt("illumination", -1);
                            int smoke = reportedProperties.optInt("smoke", -1);
                            int pm25 = reportedProperties.optInt("pm25", -1);
                            int illun = reportedProperties.optInt("illun", -1);
                            saveDataLocally(serviceId, testData, gasValue, unit, illumination, smoke, pm25, illun, eventTime);

                        } catch (Exception e) {
                            Log.e("MQTT", "解析JSON错误: " + e.getMessage());
                        }
                    }

                    @Override
                    public void deliveryComplete(IMqttDeliveryToken token) {
                        // 处理发布完成
                        Log.d("MQTT", "消息发布完成: " + token.getMessageId());
                    }
                });

                // 连接
                mqttClient.connect(options);

                // 以 QoS 1 订阅主题
                String[] topics = {shadowGetTopic, shadowResponseTopic, shadowDeltaTopic};
                int[] qos = {1, 1, 1}; // QoS=1 用于可靠传递
                mqttClient.subscribe(topics, qos);
                String requestPayload = "{ \"object_device_id\": \"IOT-TEST-001_IoT_TEST_001\",\n }";

                // 创建消息并发送到平台
                MqttMessage requestMessage = new MqttMessage(requestPayload.getBytes());
                mqttClient.publish(shadowGetTopic, requestMessage);
                Log.d("MQTT", "已发送上行请求，等待响应...");

                Log.d("MQTT", "订阅成功");

            } catch (MqttException e) {
                Log.e("MQTT", "MQTT 异常: " + e.getReasonCode() + " - " + e.getMessage(), e);
                // 处理错误
                runOnUiThread(() -> Toast.makeText(MainActivity.this, "MQTT 错误: " + e.getMessage(), Toast.LENGTH_SHORT).show());
            }
        }).start();




        // 检查并请求网络权限
        checkAndRequestPermissions();
        
        // 设置为竖屏模式
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        
        // 初始化UI
        initUI();
        
        // 初始化线程池和Handler
        executorService = Executors.newCachedThreadPool();
        mainHandler = new Handler(Looper.getMainLooper());
        
        // 初始化Rosmaster库
        rosmasterLib = new RosmasterLib(RosmasterLib.CARTYPE_X1, true);
        Log.d(TAG, "使用小车类型CARTYPE_X1(1)初始化RosmasterLib");
        rosmasterWifi = new RosmasterWifi(rosmasterLib, true);
        rosmasterWifi.init(this);
        rosmasterWifi.setServerCallback(this);
        
        // 设置按钮点击事件
        setupButtonListeners();
        
        // 更新状态
        statusText.setText("Rosmaster已初始化");
        
        // 隐藏进度条
        if (connectionProgress != null) {
            connectionProgress.setVisibility(View.GONE);
        }
        
        // 设置默认端口为控制端口
        portEdit.setText(String.valueOf(CONTROL_PORT));
        
        // 注册网络状态变化监听器
        registerNetworkReceiver();

        // 移除MQTT初始化
        // initMqtt();
    }
    private void saveDataLocally(String serviceId, int testData, int gasValue, String unit, int illumination, int smoke, int pm25, int illun, String eventTime) {
        SharedPreferences sharedPreferences = getSharedPreferences("DeviceShadowData", MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putInt("Test_data", testData);
        editor.putInt("Gas_value", gasValue);
        editor.putString("Unit", unit);
        editor.putInt("Illumination", illumination);
        editor.putInt("Smoke", smoke);
        editor.putInt("PM25", pm25);
        editor.putInt("Illun", illun);
        editor.putString("Event_time", eventTime);
        editor.apply();
        Log.d("MQTT", "数据已保存到本地");
    }
    private void initUI() {
        // 状态文本
        statusText = findViewById(R.id.status_text);
        connectionStatus = findViewById(R.id.connection_status);

        // 连接页面控件
        ipAddressEdit = findViewById(R.id.ip_address_edit);
        portEdit = findViewById(R.id.port_edit);
        connectButton = findViewById(R.id.connect_button);
        connectionProgress = findViewById(R.id.connection_progress);

        // 控制页面控件
        startServerButton = findViewById(R.id.start_server_button);

        // 根布局
        rootView = findViewById(android.R.id.content);
    }

    // ================= MQTT 相关方法 =================


    // ================= Rosmaster & 其他方法 =================

    // ... 此处省略大量 Rosmaster 相关的方法，如 setupButtonListeners, connectToRosmaster 等 ...
    // ... 它们的内容不需要修改，所以在这里折叠起来以保持简洁 ...
    //【重要】你的原始代码中，这些方法都应该保持原样

    private void checkAndRequestPermissions() {
        String[] permissions = {
                Manifest.permission.INTERNET,
                Manifest.permission.ACCESS_NETWORK_STATE,
                Manifest.permission.ACCESS_WIFI_STATE
        };

        boolean allPermissionsGranted = true;
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                allPermissionsGranted = false;
                break;
            }
        }

        if (!allPermissionsGranted) {
            ActivityCompat.requestPermissions(this, permissions, PERMISSION_REQUEST_CODE);
        }
    }

    private boolean isNetworkAvailable() {
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }

    private void setupButtonListeners() {
        // 连接按钮点击事件
        connectButton.setOnClickListener(v -> {
            String ipAddress = ipAddressEdit.getText().toString().trim();
            String portStr = portEdit.getText().toString().trim();

            if (ipAddress.isEmpty()) {
                showToast("请输入IP地址");
                return;
            }
            
            int port = CONTROL_PORT;
            if (!portStr.isEmpty()) {
                try {
                    port = Integer.parseInt(portStr);
                } catch (NumberFormatException e) {
                    showToast("端口格式错误");
                    return;
                }
            }

            connectToRosmaster(ipAddress, port);
        });

        // 启动TCP服务器按钮点击事件
        if (startServerButton != null) {
            startServerButton.setOnClickListener(v -> {
                if (!isConnected) {
                    showToast("请先连接到Rosmaster");
                    return;
                }
                
                // 启动避障服务（使用默认Docker ID）
                String dockerId = "default"; // 使用默认Docker ID
                executorService.execute(() -> {
                    try {
                        startObstacleAvoidance(dockerId);
                    } catch (Exception e) {
                        e.printStackTrace();
                        showToast("启动避障服务失败：" + e.getMessage());
                    }
                });
            });
        }
    }

    private void handleClientConnection(Socket clientSocket) {
        try {
            String clientAddress = clientSocket.getInetAddress().getHostAddress();
            Log.d(TAG, "接受来自 " + clientAddress + " 的连接");

            // 创建输入输出流
            BufferedReader reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            PrintWriter writer = new PrintWriter(clientSocket.getOutputStream(), true);

            // 发送欢迎消息
            writer.println("Welcome to Rosmaster TCP Server");

            // 处理客户端命令
            String line;
            while ((line = reader.readLine()) != null) {
                Log.d(TAG, "收到命令: " + line);

                // 处理命令
                String response = "OK";
                writer.println(response);
                }
            } catch (IOException e) {
            Log.e(TAG, "处理客户端连接时出错: " + e.getMessage());
        }
    }

    private String getLocalIpAddress() throws Exception {
        List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
        for (NetworkInterface intf : interfaces) {
            List<InetAddress> addrs = Collections.list(intf.getInetAddresses());
            for (InetAddress addr : addrs) {
                if (!addr.isLoopbackAddress() && addr instanceof Inet4Address) {
                    return addr.getHostAddress();
                }
            }
        }
        throw new Exception("No IP address found");
    }
    
    private void stopTcpServer() {
        rosmasterWifi.stopTcpServer();
        
        mainHandler.post(() -> {
            isConnected = false;
            statusText.setText("TCP服务器已停止");

            // 切换回竖屏模式
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            
            // 重置按钮状态
            startServerButton.setEnabled(true);
            
            Toast.makeText(this, "TCP服务器已停止", Toast.LENGTH_SHORT).show();
        });
    }
    
    private void disconnectFromRosmaster() {
        if (!isConnected) {
            return;
        }
        
        // 标记为已断开连接
        isConnected = false;
        
        // 使用局部变量保存引用，避免并发问题
        final RosmasterHttpClient httpClient = rosmasterHttpClient;
        final RosmasterClient tcpClient = rosmasterClient;
        
        // 执行断开连接操作
        executorService.execute(() -> {
            try {
                // 发送停止命令
                if (httpClient != null) {
                    try {
                        // 使用类型0的停止命令
                        String stopCommand = String.format("$%02x%02x%02x%02x%02x#",
                                0, 0x15, 0x04, RosmasterLib.MOTOR_STOP,
                                (0 + 0x15 + 0x04 + RosmasterLib.MOTOR_STOP) % 256);
                        
                        Log.d(TAG, "断开连接前发送停止命令: " + stopCommand);
                        httpClient.sendCommand(stopCommand);
                        
                        // 等待命令发送完成
                        Thread.sleep(200);
                    } catch (Exception e) {
                        Log.e(TAG, "发送停止命令时出错: " + e.toString());
                    }
                    
                    // 重置引用，防止使用已关闭的对象
                    rosmasterHttpClient = null;
                    
                    // 关闭连接 (在所有引用都清除后)
                    try {
                        httpClient.close();
                    } catch (Exception e) {
                        Log.e(TAG, "关闭HTTP客户端时出错: " + e.toString());
                    }
                }
                
                // 关闭Socket连接
                if (tcpClient != null) {
                    try {
                        tcpClient.close();
                    } catch (Exception e) {
                        Log.e(TAG, "关闭Socket客户端时出错: " + e.toString());
                    }
                    rosmasterClient = null;
                }
            } catch (Exception e) {
                Log.e(TAG, "断开连接时出错: " + e.toString());
            }
            
            // 更新UI
            mainHandler.post(() -> {
                // 切换回竖屏模式
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                
                // 更新状态
                statusText.setText("已断开连接");
                connectionStatus.setText("未连接");
                
                // 启用连接按钮
                connectButton.setEnabled(true);
                
                Toast.makeText(this, "已断开连接", Toast.LENGTH_SHORT).show();
            });
        });
    }
    
    // 启动追踪服务
    private void startTrackService(String dockerId) {
        if (!isConnected) {
            Toast.makeText(this, "请先连接到Rosmaster", Toast.LENGTH_SHORT).show();
            return;
        }
        
        if (rosmasterHttpClient == null) {
            Log.e(TAG, "控制错误：rosmasterHttpClient为null");
            Toast.makeText(this, "连接状态异常，请重新连接", Toast.LENGTH_SHORT).show();
            isConnected = false;
            return;
        }
        
        // 使用局部变量保存引用，避免并发问题
        final RosmasterHttpClient httpClient = rosmasterHttpClient;
        
        // 执行TCP命令，发送启动追踪命令
        executorService.execute(() -> {
            try {
                // 构造启动追踪的命令
                String command = "$START_TRACK " + dockerId + "#";
                Log.d(TAG, "发送命令: " + command);
                httpClient.sendCommand(command);
                
                // 更新UI状态
                mainHandler.post(() -> {
                    Toast.makeText(MainActivity.this, "追踪服务启动", Toast.LENGTH_SHORT).show();
                    statusText.setText("追踪服务启动");
                });
            } catch (Exception e) {
                Log.e(TAG, "启动追踪服务时出错: " + e.getMessage());
                        mainHandler.post(() -> {
                    Toast.makeText(MainActivity.this, "启动追踪服务失败", Toast.LENGTH_SHORT).show();
                });
                            }
                        });
                    }
                    
    // 停止追踪服务
    private void stopTrackService(String dockerId) {
        if (!isConnected) {
            Toast.makeText(this, "请先连接到Rosmaster", Toast.LENGTH_SHORT).show();
            return;
        }

        if (rosmasterHttpClient == null) {
            Log.e(TAG, "控制错误：rosmasterHttpClient为null");
            Toast.makeText(this, "连接状态异常，请重新连接", Toast.LENGTH_SHORT).show();
            isConnected = false;
            return;
        }

        // 使用局部变量保存引用，避免并发问题
        final RosmasterHttpClient httpClient = rosmasterHttpClient;

        // 执行TCP命令，发送停止追踪命令
        executorService.execute(() -> {
            try {
                // 构造停止追踪的命令
                String command = "$STOP_TRACK " + dockerId + "#";
                Log.d(TAG, "发送命令: " + command);
                httpClient.sendCommand(command);

                // 更新UI状态
                mainHandler.post(() -> {
                    Toast.makeText(MainActivity.this, "追踪服务已停止", Toast.LENGTH_SHORT).show();
                    statusText.setText("追踪服务已停止");
                });
            } catch (Exception e) {
                Log.e(TAG, "停止追踪服务时出错: " + e.getMessage());
                mainHandler.post(() -> {
                    Toast.makeText(MainActivity.this, "停止追踪服务失败", Toast.LENGTH_SHORT).show();
                });
            }
        });
    }
    
    // 启动避障服务
    private void startObstacleAvoidance(String dockerId) {
        if (!isConnected) {
            Toast.makeText(this, "请先连接到Rosmaster", Toast.LENGTH_SHORT).show();
            return;
        }

        if (rosmasterHttpClient == null) {
            Log.e(TAG, "控制错误：rosmasterHttpClient为null");
            Toast.makeText(this, "连接状态异常，请重新连接", Toast.LENGTH_SHORT).show();
            isConnected = false;
            return;
        }

        // 使用局部变量保存引用，避免并发问题
        final RosmasterHttpClient httpClient = rosmasterHttpClient;

        // 执行TCP命令，发送启动避障命令
        executorService.execute(() -> {
            try {
                // 构造启动避障的命令
                String command = "$START_OBSTACLE " + dockerId + "#";
                Log.d(TAG, "发送命令: " + command);
                httpClient.sendCommand(command);

                // 更新UI状态
                mainHandler.post(() -> {
                    Toast.makeText(MainActivity.this, "避障服务启动", Toast.LENGTH_SHORT).show();
                    statusText.setText("避障服务启动");
                });
            } catch (Exception e) {
                Log.e(TAG, "启动避障服务时出错: " + e.getMessage());
                mainHandler.post(() -> {
                    Toast.makeText(MainActivity.this, "启动避障服务失败", Toast.LENGTH_SHORT).show();
                });
            }
        });
    }
    
    // RosmasterWifi.ServerCallback接口实现
    @Override
    public void onClientConnected(Socket clientSocket) {
        mainHandler.post(() -> {
            isConnected = true;
            String clientAddress = clientSocket.getInetAddress().getHostAddress();
            currentIpAddress = clientAddress;
            statusText.setText("客户端已连接");
            connectionStatus.setText("客户端: " + clientAddress);
            Toast.makeText(this, "客户端已连接: " + clientAddress, Toast.LENGTH_SHORT).show();
        });
    }
    
    @Override
    public void onClientDisconnected() {
        mainHandler.post(() -> {
            isConnected = false;
            statusText.setText("客户端已断开连接");
            Toast.makeText(this, "客户端已断开连接", Toast.LENGTH_SHORT).show();
        });
    }
    
    @Override
    public void onDataReceived(String data) {
        mainHandler.post(() -> {
            Log.d(TAG, "收到数据: " + data);
        });
    }
    
    @Override
    public void onServerError(String errorMessage) {
        mainHandler.post(() -> {
            Log.e(TAG, "服务器错误: " + errorMessage);
            Toast.makeText(this, "服务器错误: " + errorMessage, Toast.LENGTH_SHORT).show();
        });
    }
    
    /**
     * 注册网络状态变化监听器
     */
    private void registerNetworkReceiver() {
        networkReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
                    boolean noConnectivity = intent.getBooleanExtra(
                            ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
                    
                    if (noConnectivity) {
                        // 网络连接丢失
                        Log.w(TAG, "网络连接丢失");
                        if (isConnected && !isServerMode) {
                            Toast.makeText(MainActivity.this, "网络连接已断开", Toast.LENGTH_SHORT).show();
                            // 如果当前已连接，则断开连接
                            disconnectFromRosmaster();
                        }
                    } else {
                        // 网络连接恢复
                        Log.d(TAG, "网络连接已恢复");
                        if (!isConnected) {
                            Toast.makeText(MainActivity.this, "网络连接已恢复", Toast.LENGTH_SHORT).show();
                        }
                    }
                }
            }
        };
        
        IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(networkReceiver, filter);
    }
    
    /**
     * 取消注册网络状态变化监听器
     */
    private void unregisterNetworkReceiver() {
        if (networkReceiver != null) {
            try {
                unregisterReceiver(networkReceiver);
            } catch (IllegalArgumentException e) {
                Log.e(TAG, "取消注册网络接收器时出错: " + e.toString());
            }
        }
    }
    
    private void showToast(String message) {
        mainHandler.post(() -> {
            Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        
        // 取消注册网络状态接收器
        unregisterNetworkReceiver();
        
        // 停止线程池
        if (executorService != null) {
            executorService.shutdown();
            try {
                if (!executorService.awaitTermination(800, TimeUnit.MILLISECONDS)) {
                    executorService.shutdownNow();
                }
            } catch (InterruptedException e) {
                executorService.shutdownNow();
            }
        }
    }

    private void connectToRosmaster(String ipAddress, int port) {
        if (isConnected) {
            showToast("已经连接到Rosmaster");
            return;
        }

        // 显示进度条
        connectionProgress.setVisibility(View.VISIBLE);
        statusText.setText("正在连接到 " + ipAddress + ":" + port);

        executorService.execute(() -> {
            try {
                // 首先检查主机是否可达
                Log.d(TAG, "开始检查主机是否可达: " + ipAddress);
                boolean hostReachable = checkHostReachable(ipAddress, port);

                if (!hostReachable) {
                    mainHandler.post(() -> {
                        connectionProgress.setVisibility(View.GONE);
                        statusText.setText("主机不可达，请检查IP地址和网络连接");
                    });
                    return;
                }

                Log.d(TAG, "主机可达，尝试连接到端口: " + port);

                // 首先尝试TCP连接
                boolean tcpConnected = false;
                boolean connected = false;

                try {
                    Socket socket = new Socket();
                    socket.connect(new java.net.InetSocketAddress(ipAddress, port), 3000);
                    socket.close();
                    tcpConnected = true;
                } catch (Exception e) {
                    Log.d(TAG, "TCP连接失败: " + e.getMessage());
                }

                if (tcpConnected) {
                    // 尝试HTTP连接
                    rosmasterHttpClient = new RosmasterHttpClient(ipAddress, port);
                    connected = true;
                    isConnected = true;

                    mainHandler.post(() -> {
                        connectionProgress.setVisibility(View.GONE);
                        statusText.setText("已连接到 " + ipAddress + ":" + port);
                        connectionStatus.setText("已连接");
                        
                        // 切换到横屏模式
                        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                        
                        connectButton.setEnabled(false);
                        // 跳转到ControlActivity
                        Intent intent = new Intent(MainActivity.this, ControlActivity.class);
                        intent.putExtra("IP_ADDRESS", ipAddress);
                        intent.putExtra("PORT", port);
                        startActivity(intent);

                        Toast.makeText(MainActivity.this, "连接成功", Toast.LENGTH_SHORT).show();
                    });
                } else {
                    mainHandler.post(() -> {
                        connectionProgress.setVisibility(View.GONE);
                        statusText.setText("连接失败");
                    });
                }
            } catch (Exception e) {
                Log.e(TAG, "连接时出错: " + e.getMessage());
                mainHandler.post(() -> {
                    connectionProgress.setVisibility(View.GONE);
                    statusText.setText("连接失败: " + e.getMessage());
                });
            }
        });
    }

    private boolean checkHostReachable(String ipAddress, int port) {
        try {
            Socket socket = new Socket();
            socket.connect(new java.net.InetSocketAddress(ipAddress, port), 3000);
            socket.close();
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}
